package com.spica.platform.user.model.resolver;

import com.spica.platform.user.model.request.SysUserQueryParam;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * sysUserParam解析
 */
public class SysUserParamResolver implements HandlerMethodArgumentResolver {
	private static final String ID = "id";
	private static final String USERNAME="username";
	private static final String NICKNAME = "nickname";
	private static final String ACCOUNTSTATUS = "accountStatus";
	private static final String TYPE = "type";
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		Class<?> cla = parameter.getParameterType();

		return cla.isAssignableFrom(SysUserQueryParam.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

		SysUserQueryParam sysUserQueryParam = new SysUserQueryParam();
		Map<String, String[]> param = request.getParameterMap();
		if (param.containsKey(ID)) {
			sysUserQueryParam.setId(Long.parseLong(request.getParameter(ID)));
		}

		if (param.containsKey(USERNAME)) {
			sysUserQueryParam.setUsername(request.getParameter(USERNAME));
		}

		if (param.containsKey(NICKNAME)) {
			sysUserQueryParam.setNickname(request.getParameter(NICKNAME));
		}

		if (param.containsKey(ACCOUNTSTATUS)) {
			sysUserQueryParam.setAccountStatus(Integer.parseInt(request.getParameter(ACCOUNTSTATUS)));
		}

		if (param.containsKey(TYPE)) {
			sysUserQueryParam.setType(Integer.parseInt(request.getParameter(TYPE)));
		}
		return sysUserQueryParam;
	}
}
